/*
 *  Copyright 2005 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.persistence.hibernate.questionnaire;

import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.model.questionnaire.Question;
import com.blandware.atleap.model.questionnaire.Questionnaire;
import com.blandware.atleap.persistence.hibernate.core.BaseDAOHibernate;
import com.blandware.atleap.persistence.questionnaire.QuestionDAO;

import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Iterator;

/**
 * <p>Hibernate implementation of QuestionDAO</p>
 * <p><a href="QuestionDAOHibernate.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.7 $ $Date: 2008/06/23 13:24:55 $
 */
public class QuestionDAOHibernate extends BaseDAOHibernate
        implements QuestionDAO {

    // ~ CRUD methods ================================================================

    /**
     * @see com.blandware.atleap.persistence.questionnaire.QuestionDAO#createQuestion(com.blandware.atleap.model.questionnaire.Question, com.blandware.atleap.model.questionnaire.Questionnaire)
     */
    public Long createQuestion(Question question, Questionnaire questionnaire) {
        question.setEncodedTitle(ConvertUtil.convertMapToByteArrays(question.getTitle()));
        question.setPosition(getFirstFreePosition(questionnaire.getId()));
        questionnaire.addQuestion(question);
        return (Long) getHibernateTemplate().save(question);
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.QuestionDAO#retrieveQuestion(Long)
     */
    public Question retrieveQuestion(Long questionId) {
        Question question = (Question) getHibernateTemplate().get(Question.class, questionId);
        question.setTitle(ConvertUtil.convertMapToStrings(question.getEncodedTitle()));
        return question;
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.QuestionDAO#updateQuestion(com.blandware.atleap.model.questionnaire.Question, com.blandware.atleap.model.questionnaire.Questionnaire)
     */
    public void updateQuestion(Question question, Questionnaire questionnaire) {
        question.setEncodedTitle(ConvertUtil.convertMapToByteArrays(question.getTitle()));
		Question oldQuestion = questionnaire.updateQuestion(question);
        removeFromCache(oldQuestion);
		getHibernateTemplate().update(question);
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.QuestionDAO#deleteQuestion(com.blandware.atleap.model.questionnaire.Question)
     */
    public void deleteQuestion(Question question) {
        getHibernateTemplate().delete(question);
        question.getQuestionnaire().removeQuestion(question);
    }

    // ~ Additional methods ================================================================

    /**
     * @see com.blandware.atleap.persistence.questionnaire.QuestionDAO#listQuestions(com.blandware.atleap.common.util.QueryInfo)   
     */
    public PartialCollection listQuestions(QueryInfo queryInfo) {
        String whereClause = new String();
        String initialWhereClause = new String();
        String orderByClause = new String();
        if ( queryInfo != null ) {
            whereClause = queryInfo.getWhereClause();
            orderByClause = queryInfo.getOrderByClause();
            if ( whereClause != null && whereClause.length() != 0 ) {
                initialWhereClause = whereClause;
                whereClause = " and " + whereClause;
            } else {
                whereClause = new String();
                initialWhereClause = new String();
            }
            if ( orderByClause != null && orderByClause.length() != 0 ) {
                orderByClause = " order by " + orderByClause;
            } else {
                orderByClause = " order by q.position ";
            }
        }

        Long questionnaireId = null;
        if ( queryInfo != null ) {
            if ( queryInfo.getQueryParameters() != null ) {
                questionnaireId = (Long) queryInfo.getQueryParameters().get("questionnaireId");
            }
        }
        List list = null;
        Integer total = null;
        ArrayList args = new ArrayList();
        String hqlPart = new String();
        if ( questionnaireId != null ) {
            hqlPart = "from Question q where (q.questionnaire.id = ?) " + whereClause;
            args.add(questionnaireId);
        } else {
            hqlPart = "from Question q where " + initialWhereClause;
        }
        if ( queryInfo != null && (queryInfo.getLimit() != null || queryInfo.getOffset() != null) ) {
            String hqlForTotal = "select count(q.id) " + hqlPart;
            total = findUniqueIntegerResult(hqlForTotal, args.toArray());
            if ( total == null ) {
                total = new Integer(0);
            }
        }
        // If we don't have any info about the total number of results yet or
        // we know that there's something that will be found, then fetch data
        if ( total == null || total.intValue() > 0 ) {
            String hql = "select q " + hqlPart + orderByClause;
            list = executeFind(hql, queryInfo, args.toArray());
            if ( total == null ) {
                total = new Integer(list.size());
            }
        } else {
            list = new ArrayList();
        }

        for (Iterator i = list.iterator(); i.hasNext(); ) {
            Question question = (Question) i.next();
            question.setTitle(ConvertUtil.convertMapToStrings(question.getEncodedTitle()));
        }

        return new PartialCollection(list, total);
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.QuestionDAO#moveQuestion(com.blandware.atleap.model.questionnaire.Question, boolean)
     */
    public void moveQuestion(Question question, boolean up) {
        Question neighbourQuestion = null;
        String hql;
        String ownerHql;
        List args;

        Long ownerId = question.getQuestionnaire().getId();
        ownerHql = "and q.questionnaire.id = ?";
        if (up) {
            hql = "select max(q.position) from Question q where q.position < ? ";
        } else {
            hql = "select min(q.position) from Question q where q.position > ? ";
        }
        String neighbourPositionHql = hql + ownerHql;
        args = new ArrayList();
        args.add(question.getPosition());
        args.add(ownerId);

        Integer neighbourPosition = findUniqueIntegerResult(neighbourPositionHql, args.toArray());
        if (neighbourPosition != null) {
            String neighbourHql = "select q from Question q where q.position = ? " + ownerHql;
            args = new ArrayList();
            args.add(neighbourPosition);
            args.add(ownerId);
            neighbourQuestion = (Question) findUniqueResult(neighbourHql, args.toArray());
            if (neighbourQuestion != null) {
                Integer tempPosition = question.getPosition();
                question.setPosition(neighbourQuestion.getPosition());
                neighbourQuestion.setPosition(tempPosition);

                getHibernateTemplate().update(question);
                getHibernateTemplate().update(neighbourQuestion);
            }
        }
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.QuestionDAO#copyQuestion(com.blandware.atleap.model.questionnaire.Question, com.blandware.atleap.model.questionnaire.Questionnaire)
     */
    public Question copyQuestion(Question question, Questionnaire questionnaire) {
        Question copy = new Question();

        copy.setTitle(new HashMap(question.getTitle()));
        copy.setEncodedTitle(new HashMap(question.getEncodedTitle()));
        copy.setType(question.getType());
        copy.setRequired(question.getRequired());
        copy.setValidationRegex(question.getValidationRegex());
        copy.setPosition(question.getPosition());
        questionnaire.addQuestion(copy);

        getHibernateTemplate().save(copy);
        return copy;
    }

    /**
     * @see com.blandware.atleap.persistence.questionnaire.QuestionDAO#getFirstLastOccupiedPositions(Long)
     */
    public Integer[] getFirstLastOccupiedPositions(Long ownerId) {
        ArrayList args = new ArrayList();
        String hql = "select min(q.position), max(q.position) from Question q where ";
        hql += "q.questionnaire.id = ?";
        args.add(ownerId);
        Object[] objs = (Object[]) findUniqueResult(hql, args.toArray());
        Integer[] result = new Integer[2];
        result[0] = (Integer) objs[0];
        result[1] = (Integer) objs[1];
        return result;
    }

    /**
     * Returns the least position available among questions with a owner with
     * given ID.
     *
     * @param ownerId ID of questionnaire which children will be considered
     * @return the least free position
     */
    protected Integer getFirstFreePosition(Long ownerId) {
        Integer result = getFirstLastOccupiedPositions(ownerId)[1];
        if (result == null) {
            result = new Integer(0);
        } else {
            result = new Integer(result.intValue() + 1);
        }
        return result;
    }
}
